package com.dtyunxi.generate.base;

import com.dtyunxi.utils.ResourceUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * <p/>
 * <br>==========================
 * <br> 公司：云徙科技
 * <br> 开发：wu.yingnan@dtyunxi.com
 * <br> 版本：1.0
 * <br> 创建时间：2017/4/11
 * <br>==========================
 */
public class CodeGenerateBase {

    /**
     * 模板文件
     */
    private String templateFile;

    /**
     * 属性
     */
    private Map<String, Object> attr = new HashMap<String, Object>();

    /**
     * 生成源文件所在目录
     */
    private String sourcePackage;

    /**
     * 生成源文件名称
     */
    private String sourceFile;

    public void generate() throws IOException, TemplateException {

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File(ResourceUtil.get("templates.dir")));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        Template temp = cfg.getTemplate(getTemplateFile());

        String projectDir = ResourceUtil.get("project.dir");
        String sourceDir = new StringBuilder(projectDir).append("/src/main/java/").append(getSourcePackage().replace(".", "/")).toString();
        File dir = new File(sourceDir);
        if (!dir.exists()) {
            boolean result = dir.mkdirs();
            System.out.println("创建文件夹结果：" + result);
        }
        OutputStream fos = new FileOutputStream(new File(dir, getSourceFile()));
        Writer out = new OutputStreamWriter(fos);
        temp.process(getAttr(), out);

        fos.flush();
        fos.close();

        System.out.println("代码生成成功!");
    }

    public String getTemplateFile() {
        return templateFile;
    }

    public void setTemplateFile(String templateFile) {
        this.templateFile = templateFile;
    }

    public Map<String, Object> getAttr() {
        return attr;
    }

    public void setAttr(Map<String, Object> attr) {
        this.attr = attr;
    }

    public String getSourcePackage() {
        return sourcePackage;
    }

    public void setSourcePackage(String sourcePackage) {
        this.sourcePackage = sourcePackage;
    }

    public String getSourceFile() {
        return sourceFile;
    }

    public void setSourceFile(String sourceFile) {
        this.sourceFile = sourceFile;
    }
}